/*
 * MainServerWindow.java
 *
 * Created on August 21, 2006, 2:04 PM
 */

package org.letva.copie.mainserver.gui;

import org.letva.copie.mainserver.*;
import java.io.*;
import javax.swing.*;
import java.util.*;
import org.letva.copie.common.message.SubServerInfo;
/**
 *
 * @author  Vuk Nikolic
 */
public class MainServerWindow extends javax.swing.JFrame {
    
    /** Creates new form MainServerWindow */
    public MainServerWindow() {
        setLookAndFeel();
        initComponents();

        String fileName = "log.txt";
        myMainServer = new MainServer(this, 7772, fileName);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        activateMainServerDialog = new javax.swing.JDialog();
        activateMainServerPanel = new javax.swing.JPanel();
        subServerPortTextField = new javax.swing.JTextField();
        subServerPortLabel = new javax.swing.JLabel();
        activateMainServerButton = new javax.swing.JButton();
        infoDialog = new javax.swing.JDialog();
        infoPanel = new javax.swing.JPanel();
        infoLabel = new javax.swing.JLabel();
        infoButton = new javax.swing.JButton();
        subServerInfoDialog = new javax.swing.JDialog();
        jPanel1 = new javax.swing.JPanel();
        subServerInfoScrollPanel = new javax.swing.JScrollPane();
        subServerInfoList = new javax.swing.JList();
        upperPanel = new javax.swing.JPanel();
        connectedSubServersLabel = new javax.swing.JLabel();
        activeSubServersLabel = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        showLogDialogItem = new javax.swing.JMenuItem();
        activateMainServerItem = new javax.swing.JMenuItem();
        showSubServerInfoItem = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        demandSubServerInfoItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        exitItem = new javax.swing.JMenuItem();

        activateMainServerDialog.setTitle("Activate Main Server");
        subServerPortTextField.setText("7772");

        subServerPortLabel.setText("Subserver Port:");

        activateMainServerButton.setText("OK");
        activateMainServerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                activateMainServerButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout activateMainServerPanelLayout = new org.jdesktop.layout.GroupLayout(activateMainServerPanel);
        activateMainServerPanel.setLayout(activateMainServerPanelLayout);
        activateMainServerPanelLayout.setHorizontalGroup(
            activateMainServerPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(activateMainServerPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(subServerPortLabel)
                .add(18, 18, 18)
                .add(subServerPortTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 87, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(211, Short.MAX_VALUE))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, activateMainServerPanelLayout.createSequentialGroup()
                .addContainerGap(236, Short.MAX_VALUE)
                .add(activateMainServerButton)
                .add(117, 117, 117))
        );
        activateMainServerPanelLayout.setVerticalGroup(
            activateMainServerPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(activateMainServerPanelLayout.createSequentialGroup()
                .add(13, 13, 13)
                .add(activateMainServerPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(subServerPortLabel)
                    .add(subServerPortTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 39, Short.MAX_VALUE)
                .add(activateMainServerButton)
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout activateMainServerDialogLayout = new org.jdesktop.layout.GroupLayout(activateMainServerDialog.getContentPane());
        activateMainServerDialog.getContentPane().setLayout(activateMainServerDialogLayout);
        activateMainServerDialogLayout.setHorizontalGroup(
            activateMainServerDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(activateMainServerPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        activateMainServerDialogLayout.setVerticalGroup(
            activateMainServerDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(activateMainServerPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        );
        infoLabel.setText("Connection Error!");

        infoButton.setText("OK");
        infoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                infoButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout infoPanelLayout = new org.jdesktop.layout.GroupLayout(infoPanel);
        infoPanel.setLayout(infoPanelLayout);
        infoPanelLayout.setHorizontalGroup(
            infoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(infoPanelLayout.createSequentialGroup()
                .add(infoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(infoPanelLayout.createSequentialGroup()
                        .add(20, 20, 20)
                        .add(infoButton))
                    .add(infoPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .add(infoLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 304, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(21, Short.MAX_VALUE))
        );
        infoPanelLayout.setVerticalGroup(
            infoPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(infoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(infoLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(infoButton)
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout infoDialogLayout = new org.jdesktop.layout.GroupLayout(infoDialog.getContentPane());
        infoDialog.getContentPane().setLayout(infoDialogLayout);
        infoDialogLayout.setHorizontalGroup(
            infoDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(infoPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        infoDialogLayout.setVerticalGroup(
            infoDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(infoPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        );
        subServerInfoDialog.setTitle("Subserver Info");
        subServerInfoList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        subServerInfoScrollPanel.setViewportView(subServerInfoList);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(subServerInfoScrollPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 339, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(84, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(subServerInfoScrollPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(65, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout subServerInfoDialogLayout = new org.jdesktop.layout.GroupLayout(subServerInfoDialog.getContentPane());
        subServerInfoDialog.getContentPane().setLayout(subServerInfoDialogLayout);
        subServerInfoDialogLayout.setHorizontalGroup(
            subServerInfoDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        subServerInfoDialogLayout.setVerticalGroup(
            subServerInfoDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Main Server");
        connectedSubServersLabel.setText("Connected Subservers:");

        activeSubServersLabel.setText("0");

        org.jdesktop.layout.GroupLayout upperPanelLayout = new org.jdesktop.layout.GroupLayout(upperPanel);
        upperPanel.setLayout(upperPanelLayout);
        upperPanelLayout.setHorizontalGroup(
            upperPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(upperPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(connectedSubServersLabel)
                .add(17, 17, 17)
                .add(activeSubServersLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(106, Short.MAX_VALUE))
        );
        upperPanelLayout.setVerticalGroup(
            upperPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(upperPanelLayout.createSequentialGroup()
                .add(31, 31, 31)
                .add(upperPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(connectedSubServersLabel)
                    .add(activeSubServersLabel))
                .addContainerGap(55, Short.MAX_VALUE))
        );

        fileMenu.setMnemonic('f');
        fileMenu.setText("File");
        showLogDialogItem.setText("Change Log File");
        showLogDialogItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showLogDialogItemActionPerformed(evt);
            }
        });

        fileMenu.add(showLogDialogItem);

        activateMainServerItem.setMnemonic('a');
        activateMainServerItem.setText("Activate Main Server");
        activateMainServerItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                activateMainServerItemActionPerformed(evt);
            }
        });

        fileMenu.add(activateMainServerItem);

        showSubServerInfoItem.setMnemonic('s');
        showSubServerInfoItem.setText("Show Subserver Info");
        showSubServerInfoItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showSubServerInfoItemActionPerformed(evt);
            }
        });

        fileMenu.add(showSubServerInfoItem);

        fileMenu.add(jSeparator2);

        demandSubServerInfoItem.setMnemonic('d');
        demandSubServerInfoItem.setText("Demand SubServer Info");
        demandSubServerInfoItem.setEnabled(false);
        demandSubServerInfoItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                demandSubServerInfoItemActionPerformed(evt);
            }
        });

        fileMenu.add(demandSubServerInfoItem);

        fileMenu.add(jSeparator1);

        exitItem.setMnemonic('e');
        exitItem.setText("Exit");
        exitItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitItemActionPerformed(evt);
            }
        });

        fileMenu.add(exitItem);

        menuBar.add(fileMenu);

        setJMenuBar(menuBar);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(upperPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(upperPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void showLogDialogItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showLogDialogItemActionPerformed
        JFileChooser fc = new JFileChooser();
        String fileName = "log.txt";
        int result = fc.showOpenDialog(this);
        switch(result) {
           case JFileChooser.APPROVE_OPTION:
               // znaci rekli smo izaberi taj fajl
                // ovde pravim fajl
               File newFile = fc.getSelectedFile(); 
               fileName = newFile.getAbsolutePath();
              break;
           case JFileChooser.CANCEL_OPTION: break;
           case JFileChooser.ERROR_OPTION: break;
        }
        showLogDialogItem.setEnabled(false);
    }//GEN-LAST:event_showLogDialogItemActionPerformed

    private void demandSubServerInfoItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_demandSubServerInfoItemActionPerformed
        Map<String, SubServerInfo> ss = myMainServer.getSubServers();
        Set entries = ss.entrySet();
        Iterator entryIter = entries.iterator();
        while (entryIter.hasNext()) {
            Map.Entry entry = (Map.Entry)entryIter.next();
            Object key = entry.getKey();  // Get the key from the entry.
            Object value = entry.getValue();  // Get the value.
            Thread t = new SubServerOnDemandThread(myMainServer,(SubServerInfo) value);
            t.start();
            myMainServer.writeLog("SubServerOnDemand: " + key);
        }
    }//GEN-LAST:event_demandSubServerInfoItemActionPerformed

    private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitItemActionPerformed

    private void showSubServerInfoItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showSubServerInfoItemActionPerformed
        // ovde sad treba da dohvatimo sve subServere sto imamo i ih stavimo
        // u listu. posto neko moze da ih dodaje i menja mora biti synchronized
        Map<String, SubServerInfo> subServers = new HashMap();
        
        synchronized(myMainServer){
            subServers = myMainServer.getSubServers();
        }
        
        LinkedList ll = new LinkedList(subServers.values());

        Object[] objects = new Object[0];
        if (ll != null){
            objects = new Object[ll.size()];
            for (int i = 0; i < ll.size(); i++){
                SubServerInfo ssi = ((SubServerInfo)ll.get(i));
                String status = "not available";
                if (ssi.getClipboardStatus() == true){
                    status = "available";
                }
                String s = ssi.getUrl() + "       " + ssi.getNetworkOperations() + "       " +status;
                objects[i] = s;
            }

        } 

        subServerInfoList.setListData(objects);
        subServerInfoDialog.setBounds(getX(), getY(), 370, 185);
        subServerInfoDialog.setVisible(true);
  
    }//GEN-LAST:event_showSubServerInfoItemActionPerformed

    private void infoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_infoButtonActionPerformed
        infoDialog.setVisible(false);
    }//GEN-LAST:event_infoButtonActionPerformed

    private void activateMainServerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_activateMainServerButtonActionPerformed
        myMainServer.start();
        activateMainServerItem.setEnabled(false);
        try {
            myMainServer.setSubServerPort(Integer.parseInt(subServerPortTextField.getText()));
            demandSubServerInfoItem.setEnabled(true);
            activateMainServerDialog.setVisible(false);
        } catch (NumberFormatException ex) {
            setDialogException("Port Format Error", "Port must be an integer!");
        }
        
    }//GEN-LAST:event_activateMainServerButtonActionPerformed

    private void activateMainServerItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_activateMainServerItemActionPerformed
        activateMainServerDialog.setBounds(getX(), getY(), 300, 150);
        activateMainServerDialog.setVisible(true);
    }//GEN-LAST:event_activateMainServerItemActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainServerWindow().setVisible(true);
            }
        });
    }
    
    
    public void setDialogException(int x, int y, String title, String text){
        infoDialog.setTitle(title);
        infoDialog.setBounds(this.getX(), this.getY(), x, y);
        infoLabel.setText(text);
        infoDialog.setVisible(true);
    } 
    
    public void setDialogException(String title, String text){
        setDialogException(200, 100, title, text);
    } 
    
    public void setActiveSubServersLabel(){
        activeSubServersLabel.setText(myMainServer.getActiveSubServerThreads() + "");
    }
    
    private static void setLookAndFeel(){
           
    // Install a different look and feel; specifically, the Windows look and feel
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (InstantiationException e) {
        } catch (ClassNotFoundException e) {
        } catch (UnsupportedLookAndFeelException e) {
        } catch (IllegalAccessException e) {
        }
    }
        
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton activateMainServerButton;
    private javax.swing.JDialog activateMainServerDialog;
    private javax.swing.JMenuItem activateMainServerItem;
    private javax.swing.JPanel activateMainServerPanel;
    private javax.swing.JLabel activeSubServersLabel;
    private javax.swing.JLabel connectedSubServersLabel;
    private javax.swing.JMenuItem demandSubServerInfoItem;
    private javax.swing.JMenuItem exitItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JButton infoButton;
    private javax.swing.JDialog infoDialog;
    private javax.swing.JLabel infoLabel;
    private javax.swing.JPanel infoPanel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem showLogDialogItem;
    private javax.swing.JMenuItem showSubServerInfoItem;
    private javax.swing.JDialog subServerInfoDialog;
    private javax.swing.JList subServerInfoList;
    private javax.swing.JScrollPane subServerInfoScrollPanel;
    private javax.swing.JLabel subServerPortLabel;
    private javax.swing.JTextField subServerPortTextField;
    private javax.swing.JPanel upperPanel;
    // End of variables declaration//GEN-END:variables
    
    MainServer myMainServer = null;
}
